//
//  GYDKeyboardView.swift
//  Weibo
//
//  Created by 贵永冬 on 16/8/1.
//  Copyright © 2016年 贵永冬. All rights reserved.
//

import UIKit

class GYDKeyboardView: UIView, UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate {


    var lastButton : UIButton?
    
    var pageContorl : UIPageControl?
    
    var collectionView : UICollectionView?
    
    var currentIndex : Int = 1
    
    var dataSoure : [GYDKeyboardEmoticon]?
    
    var emoticonBlock : ((emoticon : GYDKeyboardEmoticon) -> ())?
    
    lazy var packages : [GYDKeyboardPackage] = {
        return GYDKeyboardPackage.loadEmoticonPackages()
    }()

    override init(frame: CGRect) {
        
        let height = GYDWindowWidth/7.0*3.0 + 65
        super.init(frame: CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: height))
        self.backgroundColor = RGB(250, g: 250, b: 250)
        createCollectionView()
        createPageContorl()
        createBottomView()
        
        
        let lineView = UIView(frame: CGRect(x: 0, y: 0, width: self.width, height: 0.5))
        lineView.backgroundColor =  RGB(210, g: 210, b: 210)
        self.addSubview(lineView)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func createCollectionView() {
        let layOut = GYDKeyboardLayout()
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.width, height: self.height - 65) , collectionViewLayout: layOut)
        self.addSubview(collectionView)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.pagingEnabled = true
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = RGB(250, g: 250, b: 250)
        collectionView.bounces = false
        self.collectionView = collectionView
        self.dataSoure = self.packages[1].emoticons
        collectionView.registerClass(GYDKeyboardCell.classForCoder(), forCellWithReuseIdentifier: "cellId")
    }
    
    private func createPageContorl() {
        let pageContorl = UIPageControl(frame: CGRect(x: 0, y: self.height - 40 - 25, width: GYDWindowWidth, height: 15))
        pageContorl.numberOfPages = Int((self.packages[1].emoticons?.count)!/21)
        pageContorl.currentPage = 0
        pageContorl.setValue(UIImage(named:"compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pageContorl.setValue(UIImage(named:"compose_keyboard_dot_normal"), forKey: "_pageImage")
        self.pageContorl = pageContorl
        self.addSubview(pageContorl)
    }
    
    private func createBottomView() {
        let bottomView = UIView(frame: CGRect(x: 0, y: self.height - 40, width: self.width, height: 40))
        self.addSubview(bottomView)
        
        let titleArray = ["最近","默认","Emoji","浪小花"]
        let width : CGFloat = self.width / CGFloat(titleArray.count)
        for i in 0 ..< titleArray.count {
            let title = titleArray[i]
            let button = UIButton(type: UIButtonType.Custom)
            button.frame = CGRect(x: CGFloat(i)*width, y: 0, width: width, height: 40)
            bottomView.addSubview(button)
            button.tag = 80+i
            button.titleLabel?.font = UIFont.systemFontOfSize(15)
            button.setTitle(title, forState: UIControlState.Normal)
            button.setTitleColor(RGB(190, g: 190, b: 190), forState: UIControlState.Normal)
            button.setTitleColor(RGB(100, g: 100, b: 100), forState: UIControlState.Selected)
            if i == 1 {
                self.lastButton = button
                button.selected = true
                button.backgroundColor = RGB(230, g: 230, b: 230)
            }else {
                button.backgroundColor = RGB(240, g: 240, b: 240)
            }
            
            button.addTarget(self, action: #selector(GYDKeyboardView.buttonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        }
        let lineView = UIView(frame: CGRect(x: 0, y: 0, width: self.width, height: 0.5))
        lineView.backgroundColor =  RGB(210, g: 210, b: 210)
        bottomView.addSubview(lineView)
        
    }
    
    @objc private func buttonClick(btn : UIButton) {
        if self.lastButton == btn {
            return
        }
        self.lastButton?.selected = false
        self.lastButton?.backgroundColor = RGB(240, g: 240, b: 240)
        btn.backgroundColor = RGB(230, g: 230, b: 230)
        btn.selected = true
        self.lastButton = btn
        self.currentIndex = btn.tag - 80
        pageContorl!.numberOfPages = Int((self.packages[self.currentIndex].emoticons?.count)!/21)
        pageContorl?.currentPage = 0
        self.dataSoure = self.packages[self.currentIndex].emoticons
        self.collectionView?.reloadData()
        self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    
    //MARK: -UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSoure?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath) as! GYDKeyboardCell
        cell.emoticon = dataSoure![indexPath.item]
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emotion = dataSoure![indexPath.item]
        if emotion.isRemoveButton {
            if self.emoticonBlock != nil {
                self.emoticonBlock!(emoticon: emotion)
            }
        }else {
            if emotion.id != nil {
                if self.emoticonBlock != nil {
                    self.emoticonBlock!(emoticon: emotion)
                }
                packages[0].addNewEmoticon(emotion)
            }
        }
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let index = scrollView.contentOffset.x / scrollView.width
        pageContorl?.currentPage = Int(index)
    }
}


class GYDKeyboardCell: UICollectionViewCell {
    /// 当前行对应的表情模型
    var emoticon: GYDKeyboardEmoticon?
        {
        didSet{
            // 1.显示emoji表情
            iconButton.setTitle(emoticon?.emoticonStr ?? "", forState: UIControlState.Normal)
            
            // 2.设置图片表情
            iconButton.setImage(nil, forState: UIControlState.Normal)
            if emoticon?.chs != nil
            {
                if emoticon!.pngPath != nil {
                    iconButton.setImage(UIImage(contentsOfFile: emoticon!.pngPath!), forState: UIControlState.Normal)
                }
            }
            // 3.设置删除按钮
            if emoticon!.isRemoveButton
            {
                iconButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = RGB(250, g: 250, b: 250)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    // MARK: - 内部控制方法
    private func setupUI()
    {
        // 1.添加子控件
        contentView.addSubview(iconButton)
        iconButton.backgroundColor = RGB(250, g: 250, b: 250)
        iconButton.userInteractionEnabled = false
        // 2.布局子控件
        iconButton.frame = CGRectInset(bounds, 4, 4)
    }
    
    // MARK: - 懒加载
    private lazy var iconButton: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFontOfSize(30)
        return btn
    }()
}

class GYDKeyboardLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        itemSize = CGSize(width: GYDWindowWidth/7.0, height: GYDWindowWidth/7.0)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
    }
}






